define(['jquery', 'vue', 'axios'], function ($, Vue, axios) {
    // 确保 Vue 和 axios 正确引入
    Vue.prototype.$axios = axios;

    var ManagerBox = {
        props: ['user_id', 'type', 'leftOptions', 'rightOptions'],
        template: `
            <div class="manager-box" @mouseleave="handleMouseLeave">
                <div class="select-container">
                    <div class="label" style="color:#000">已选</div>
                    <select v-model="selectedLeft" :name="type === 'single' ? 'row[manager_id][]' : 'row[manager_id][]'"
                        class="form-control mustselected" :multiple="type !== 'single'" size="10"
                        @dblclick="moveRight" style="height:229px">
                        <option v-for="option in localLeftOptions" :key="option.value" :value="option.value" :selected="type === 'single' && selectedLeft.includes(option.value)"
                            v-if="option.group_id === 3">
                            {{ option.text }} ({{ option.phone }})
                        </option>
                    </select>
                </div>
                <div class="button-container">
                    <button @click="moveRight" tabindex="-1">>></button>
                    <button @click="moveLeft" tabindex="-1"><<</button>
                </div>
                <div class="select-container">
                    <div class="label" style="color:#000">备选</div>
                    <input type="text" class="searchQuery" v-model="searchQuery" placeholder="查询手机号、姓名"
                        @blur="fetchRightOptions" @keyup.enter="fetchRightOptions"/>
                    <select v-model="selectedRight" class="form-control" multiple size="10" @dblclick="moveLeft">
                        <option v-for="option in filteredRightOptions" :key="option.value" :value="option.value"
                            v-if="option.group_id === 3">
                            {{ option.text }} ({{ option.phone }})
                        </option>
                    </select>
                </div>
            </div>
        `,
        data() {
            return {
                localLeftOptions: [],
                localRightOptions: [],
                selectedLeft: [],
                selectedRight: [],
                searchQuery: '',
            };
        },
        computed: {
            filteredRightOptions() {
                if (!this.searchQuery) return this.localRightOptions;
                const query = this.searchQuery.toLowerCase();
                return this.localRightOptions.filter(option =>
                    option.text.toLowerCase().includes(query) ||
                    option.phone.includes(query)
                );
            },
            filteredOptions() {
                return this.localRightOptions.filter(option => option.group_id === 3);
            }
        },
        created() {
            this.localLeftOptions = [...this.leftOptions];
            this.localRightOptions = [...this.rightOptions];
            this.selectAllLeftOptions();
        },
        methods: {
            handleMouseLeave() {
                if (!this.selectedLeft.length) {
                    this.selectAllLeftOptions();
                }
            },
            selectAllLeftOptions() {
                if (Array.isArray(this.leftOptions)) {
                    this.selectedLeft = this.type === 'single'
                        ? (this.leftOptions.length > 0 ? [this.leftOptions[0].value] : [])
                        : this.leftOptions.map(option => option.value);
                } else {
                    this.selectedLeft = [];
                }
                this.selectedLeft = this.type === 'single' ? (this.localLeftOptions.length > 0 ? [this.localLeftOptions[0].value] : []) : this.localLeftOptions.map(option => option.value);
            },
            moveRight(event) {
                event.stopPropagation();
                event.preventDefault();
                const selectedItems = this.selectedLeft.map(item => this.localLeftOptions.find(option => option.value === item));
                selectedItems.forEach(item => {
                    const index = this.localLeftOptions.findIndex(option => option.value === item.value);
                    if (index !== -1) {
                        this.localLeftOptions.splice(index, 1);
                    }
                });
                this.localRightOptions.push(...selectedItems);
                this.selectedLeft = [];
                this.selectAllLeftOptions();
            },
            moveLeft(event) {
                event.stopPropagation();
                event.preventDefault();
                const selectedItems = this.selectedRight.map(item => this.localRightOptions.find(option => option.value === item));
                if (this.type === 'single') {
                    if (selectedItems.length > 0) {
                        this.localLeftOptions = [selectedItems[0]];
                    }
                } else {
                    selectedItems.forEach(item => {
                        const index = this.localRightOptions.findIndex(option => option.value === item.value);
                        if (index !== -1) {
                            this.localRightOptions.splice(index, 1);
                        }
                    });
                    this.localLeftOptions.push(...selectedItems);
                }
                this.selectedRight = [];
                this.selectAllLeftOptions();
            },
            fetchRightOptions() {
                let url = '/user/user/lists?groupId=3';
                if (this.searchQuery) {
                    url = `/user/user/lists?groupId=3&q=${encodeURIComponent(this.searchQuery)}`;
                }
                this.localRightOptions = [];
                this.$axios.get(url).then(response => {
                    const leftValues = this.localLeftOptions.map(option => option.value);
                    this.localRightOptions = response.data.list.filter(item => !leftValues.includes(item.value));
                });
            },
            fetchLeftOptions() {
                this.localLeftOptions = this.leftOptions
                    .filter(item => item.group_id === 3)
                    .map(item => ({
                        value: item.value,
                        text: item.text,
                        phone: item.phone
                    }));
            }
        },
        watch: {
            leftOptions: {
                handler(newVal) {
                    if (Array.isArray(newVal)) {
                        this.selectAllLeftOptions();
                    }
                },
                deep: true,
                immediate: true
            }
        },
        mounted() {
            const uniqueAttr = 'data-manager-box';
            const style = document.createElement('style');
            style.innerHTML = `
                .manager-box[${uniqueAttr}] {
                    display: flex;
                    justify-content: space-between;
                    align-items: stretch;
                }
                .manager-box[${uniqueAttr}] .select-container {
                    display: flex;
                    flex-direction: column;
                    width: 200px;
                }
                .manager-box[${uniqueAttr}] .label {
                    font-weight: bold;
                    margin-bottom: 5px;
                    color: black!important;
                }
                .manager-box[${uniqueAttr}] .form-control {
                    width: 100%;
                    height: 200px;
                }
                .manager-box[${uniqueAttr}] .button-container {
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    min-height: 200px;
                }
                .manager-box[${uniqueAttr}] .button-container button {
                    margin: 5px 0;
                }
            `;
            document.head.appendChild(style);
            this.$el.setAttribute(uniqueAttr, '');
        }
    };

    Vue.component('manager-box', ManagerBox);

    if (typeof module !== 'undefined' && module.exports) {
        module.exports = ManagerBox;
    }
});